<?php

namespace app\common\components;

use yii\web\Controller;
use yii\web\Response;

/**
 * 集成公用方法 提供所有的controller使用
 *get,post,setCookie,renderJson
 */
class BaseWebController extends Controller
{
    public $enableCsrfValidation = false;

    //获取http的get参数
    public function get($key, $default_val = "")
    {
        return \yii::$app->request->get($key, $default_val);
    }

    //获取http的post参数
    public function post($key, $default_val = "")
    {
        return \yii::$app->request->post($key, $default_val);
    }

    //设置cookie
    public function setCookie($name, $val, $expire = 0)
    {
        $cookies = \yii::$app->response->cookies;

        $cookies->add(new \yii\web\Cookie([
            'name' => $name,
            'value' => $val,
            'expire' => $expire,
        ]));
    }

    //获取cookie
    public function getCookie($name, $default_val = "")
    {
        $cookies = \yii::$app->request->cookies;

        return $cookies->getValue($name, $default_val);
    }

    //删除cookie

    /**
     * @param $name
     * @param string $default_val
     */
    public function removeCookie($name, $default_val = "")
    {
        $cookies = \yii::$app->response->cookies;

        $cookies->remove($name);
    }

    //api 返回格式

    /**
     * @param array $data
     * @param string $msg
     * @param int $code
     * @return mixed
     */
    public function renderJson($data = [], $msg = "ok", $code = 200)
    {
//        \Yii::$app->response->format = Response::FORMAT_JSON;
//
//        $json = [
//            "code" => $code,
//            "msg" => $msg,
//            "data" => $data,
//            "req_id" => uniqId(),
//        ];
//        return $json;
        header('Content-type: application/json');
        echo json_encode([
            "code" => $code,
            "msg" => $msg,
            "data" => $data,
            "req_id" => $this->uniqueId,
        ]);

        return \Yii::$app->end();
    }

    //统一js提醒
    public function renderJs($msg, $url)
    {
        return $this->renderPartial("@app/views/common/js", ["msg" => $msg, "url" => $url]);
    }

}
